package com.tuananh.radnom.persist.imp.xml;

import java.util.ArrayList;
import java.util.HashMap;

import com.ajexperience.utils.DeepCopyException;
import com.ajexperience.utils.DeepCopyUtil;
import com.tuananh.radnom.model.netpoller.PollingConfiguration;
import com.tuananh.radnom.model.userinfo.User;
import com.tuananh.radnom.model.userinfo.UserConfiguration;
import com.tuananh.radnom.model.userinfo.UserGroup;
import com.tuananh.radnom.persist.AbstractPersitor;
import com.tuananh.radnom.persist.IUserDAO;

public class UserXmlDAO extends XmlDAO implements IUserDAO {
	UserConfiguration userConfig;

	public UserXmlDAO() {
		super(UserConfiguration.path);
		configuration = XmlConfigHolder.userConfig;
		try {
			savedConfiguration = (new DeepCopyUtil()).deepCopy(configuration);
		} catch (DeepCopyException e) {
			// TODO Auto-generated catch block
			savedConfiguration = new UserConfiguration();
			e.printStackTrace();
		}
		userConfig = (UserConfiguration) configuration;
	}

	public ArrayList<User> getAllUser() {
		// TODO Auto-generated method stub
		return userConfig.getUser();
	}

	public ArrayList<UserGroup> getAllGroup() {
		// TODO Auto-generated method stub
		return userConfig.getGroup();
	}

	public User getUserByName(String userName) {
		// TODO Auto-generated method stub
		for (User usr : userConfig.getUser()) {
			if (usr.getName().equals(userName)) {
				return usr;
			}
		}
		return null;
	}

	public ArrayList<User> getUserFromGroup(String groupName) {
		// TODO Auto-generated method stub
		UserGroup group = getGroupByName(groupName);
		if (group!=null)
			return group.getUsers();
		return null;
	}

	public UserGroup getGroupByName(String groupName) {
		// TODO Auto-generated method stub
		for(UserGroup group:userConfig.getGroup()){
			if (group.getName().equals(groupName)){
				return group;
			}
		}
		return null;
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "UserEvent";
	}

	public ArrayList<User> getAllByNamesGroups(ArrayList<String> usrNames,
			ArrayList<String> groupNames) {
		// TODO Auto-generated method stub
		HashMap<String, User> hashmap = new HashMap<String, User>();
		for(String name:usrNames){
			User usr = getUserByName(name);
			if (usr!=null){
				hashmap.put(usr.getName(), usr);
			}
		}
		
		for(String groupName:groupNames){
			UserGroup group = getGroupByName(groupName);
			if (group!=null){
				if (group.getUsers()!=null){
					for(User usr:group.getUsers()){
						hashmap.put(usr.getName(), usr);
					}
				}
			}
		}
		ArrayList<User> result = new ArrayList<User>(hashmap.values());
		return result;
	}

}
